package com.lancoo.tyjx.multichatroom.db;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import com.lancoo.tyjx.multichatroom.constants.Constants;
import com.lancoo.tyjx.multichatroom.model.ChatItem;

import java.util.ArrayList;
import java.util.List;


public class MsgDbHelper {
    private static final String TAG = "MsgDbHelper";

    private static MsgDbHelper instance = null;

    private SqlLiteHelper helper;
    private SQLiteDatabase db;  // 我的最新聊天信息
    private final int SHOW_MSG_COUNT = 15;
    /**
     * 10
     */
    private final int MORE_MSG_COUNT = 10;

    public MsgDbHelper(Context context) {
        helper = new SqlLiteHelper(context);
        db = helper.getWritableDatabase();
        helper.onCreate(db);
    }

    public void closeDb() {
        db.close();
        helper.close();
    }

    public static MsgDbHelper getInstance(Context context) {
        if (instance == null) {
            instance = new MsgDbHelper(context);
        }
        return instance;
    }

    private class SqlLiteHelper extends SQLiteOpenHelper {

        private static final int DB_VERSION = 1;
        private static final String DB_NAME = "chat";

        public SqlLiteHelper(Context context) {
            super(context, DB_NAME, null, DB_VERSION);
        }

        /* (non-Javadoc)
         *
    public String chatName;  //群聊的话跟username不一样
    private String username;  //对方的昵称
    private String head;
    private String msg;
    private String sendDate;
    private int inOrOut; //0代表in 1代表out
    private String whos;
    private int sendState;//0代表正在发送，1代表发送成功，2代表发送失败
         */
        @Override
        public void onCreate(SQLiteDatabase db) {
            String sql = "CREATE TABLE  IF NOT EXISTS " + DB_NAME
                    + "( id INTEGER PRIMARY KEY AUTOINCREMENT,chatType INTEGER,chatName text," +
                    "username text , head text ,msg text,sendDate text,inOrOut INTEGER,sendState INTEGER,voicetime INTEGER,fileName text,fileUrl text,msgType text,whos text,i_filed INTEGER,t_field text)";
            db.execSQL(sql);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            dropTable(db);
            onCreate(db);
        }

        private void dropTable(SQLiteDatabase db) {
            String sql = "DROP TABLE IF EXISTS " + DB_NAME;
            db.execSQL(sql);
        }

    }

    public void saveChatMsg(ChatItem msg) {
        ContentValues values = new ContentValues();
        values.put("chatName", msg.chatName);
        values.put("whos", Constants.USER_NAME);
        values.put("chatType", msg.chatType);
        values.put("username", msg.username);
        values.put("head", msg.head);
        values.put("msg", msg.msg);
        values.put("inOrOut", msg.inOrOut);
        values.put("msgType", msg.getMsgType());
        values.put("sendDate", msg.sendDate);
        values.put("sendState", msg.sendState);
        values.put("voicetime", msg.voicetime);
        values.put("fileName", msg.fileName);
        values.put("fileUrl", msg.fileUrl);
        if (isExist(msg)) {
            Log.w(TAG, "已经存在");
            return;
        }
        db.insert(helper.DB_NAME, "id", values);
    }

    /**
     * 检查是否存在
     *
     * @param msg
     * @return
     */
    public boolean isExist(ChatItem msg) {
        String sql = "select * from  " + helper.DB_NAME +
                " where username = ?  " +
                "and msg = ? " +
                "and sendDate = ? " +
                "and whos = ? " +
                "and chatName = ? " +
                "and chatType = ? " +
                "and head = ? " +
                "and inOrOut = ?";
        Cursor cursor = db.rawQuery(sql, new String[]{
                msg.username,
                msg.msg,
                msg.sendDate,
                Constants.USER_NAME,
                msg.chatName,
                msg.chatType + "",
                msg.head,
                msg.inOrOut + ""});
        int count = cursor.getCount();
        if (count > 0) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 更新发送的消息的发送状态
     *
     * @param msg
     */
    public void updateMsgSendState(ChatItem msg) {
        String sql = "update " + helper.DB_NAME + " set sendState=" + msg.sendState + " where chatType="
                + msg.chatType + " and chatName='" + msg.chatName + "' and msg='" + msg.msg + "' and inOrOut=1 "
                + "and sendState=0";
        db.execSQL(sql);
    }

    /**
     * 取当前会话窗口的聊天记录，限量count
     *
     * @param chatName
     */
    public List<ChatItem> getChatMsg(String chatName) {
        List<ChatItem> chatItems = new ArrayList<ChatItem>();
        ChatItem msg;
        String sql = "select a.chatType,a.chatName,a.username,a.head,a.msg,a.sendDate,a.inOrOut,a.sendState,a.voicetime,a.fileName,a.fileUrl,a.msgType" +
                " from(select * from " + helper.DB_NAME +
                " where chatName = ? and whos = ? order by id desc LIMIT " + SHOW_MSG_COUNT + ")a order by a.id";
        if (null == chatName || null == Constants.USER_NAME) {
            return null;
        }
        Cursor cursor = db.rawQuery(sql, new String[]{chatName, Constants.USER_NAME});
        while (cursor.moveToNext()) {
            msg = new ChatItem(cursor.getInt(0), cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4)
                    , cursor.getString(5), cursor.getInt(6), cursor.getInt(7));
            msg.setVoicetime(cursor.getInt(8));
            msg.setFileName(cursor.getString(9));
            msg.setFileUrl(cursor.getString(10));
            msg.setMsgType(cursor.getString(11));
            chatItems.add(msg);
            msg = null;
        }
        cursor.close();
        return chatItems;
    }


    /**
     * 获取更多好友聊天记录,显示多5条
     *
     * @param startIndex
     * @param chatName
     */
    public List<ChatItem> getChatMsgMore(int startIndex, String chatName) {
        List<ChatItem> chatItems = new ArrayList<>();
        ChatItem msg;
        String sql = "select a.chatType,a.chatName,a.username,a.head,a.msg,a.sendDate,a.inOrOut,a.sendState,a.voicetime " +
                " from(select * from " + helper.DB_NAME +
                " where chatName = ? and whos = ? order by id desc LIMIT " + MORE_MSG_COUNT + " offset " + startIndex + ")a order by a.id";
        Cursor cursor = db.rawQuery(sql, new String[]{chatName, Constants.USER_NAME});
        while (cursor.moveToNext()) {
            msg = new ChatItem(cursor.getInt(0), cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4)
                    , cursor.getString(5), cursor.getInt(6), cursor.getInt(7));
            msg.setVoicetime(cursor.getInt(8));
            chatItems.add(msg);
            msg = null;
        }
        cursor.close();
        return chatItems;
    }

    /**
     * 获取最新的消息
     *
     * @return
     */
    public ChatItem getNewMsg() {
        ChatItem msg = null;
        String sql = "SELECT * from " + helper.DB_NAME + " where id ORDER BY sendDate DESC LIMIT 1";
        final Cursor cursor = db.rawQuery(sql, null);
        while (cursor.moveToNext()) {
            msg = new ChatItem(cursor.getInt(0), cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4)
                    , cursor.getString(5), cursor.getInt(6), cursor.getInt(7));
        }
        cursor.close();
        return msg;
    }

    /**
     * 取得我的的最新消息，显示在好友表
     */
    @SuppressWarnings("unused")
    public List<ChatItem> getLastMsg() {
        List<ChatItem> chatItems = new ArrayList<ChatItem>();
        ChatItem msg;
        String sql = "select chatType,chatName,username,head,msg,sendDate,inOrOut,sendState ,voicetime  from  " + helper.DB_NAME +
                " where whos = ? " +
                " GROUP BY chatName " +
                "order by id desc";
        final Cursor cursor = db.rawQuery(sql, new String[]{Constants.USER_NAME});
        while (cursor.moveToNext()) {
            msg = new ChatItem(cursor.getInt(0), cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4)
                    , cursor.getString(5), cursor.getInt(6), cursor.getInt(7));
            msg.setVoicetime(cursor.getInt(8));
            chatItems.add(msg);
            msg = null;
        }
        cursor.close();
        return chatItems;
    }


    /**
     * 取得我的的最新消息，模糊搜索,显示在好友表
     */
    @SuppressWarnings("unused")
    public List<ChatItem> getLastMsg(String keywords) {
        List<ChatItem> chatItems = new ArrayList<ChatItem>();
        ChatItem msg;
        String sql = "select chatType,chatName,username,head,msg,sendDate,inOrOut,sendState,voicetime from  " + helper.DB_NAME +
                " where username like ? and whos = ? " +
                " GROUP BY chatName " +
                " order by id desc";
        final Cursor cursor = db.rawQuery(sql, new String[]{"%" + keywords + "%", Constants.USER_NAME});
        while (cursor.moveToNext()) {
            msg = new ChatItem(cursor.getInt(0), cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4)
                    , cursor.getString(5), cursor.getInt(6), cursor.getInt(7));
            msg.setVoicetime(cursor.getInt(8));
            chatItems.add(msg);
            msg = null;
        }
        cursor.close();
        return chatItems;
    }

    public void delChatMsg(String msgId) {
        db.delete(helper.DB_NAME, "chatName=? and whos=?", new String[]{msgId, Constants.USER_NAME});
    }

    public void clear() {
        db.delete(helper.DB_NAME, "id>?", new String[]{"0"});
    }
}
